// Chrome 65兼容版本 - popup.js
// 移除所有ES6+语法，使用ES5语法重写

document.addEventListener('DOMContentLoaded', function () {
  console.log('Chrome 65兼容版 popup.js 已加载');

  // 获取DOM元素
  var enableNotificationsCheckbox = document.getElementById('enableNotifications');
  var enableSoundCheckbox = document.getElementById('enableSound');
  var alertIntervalInput = document.getElementById('alertInterval');
  var soundTypeSelect = document.getElementById('soundType');
  var saveButton = document.getElementById('saveSettings');
  var statusDiv = document.getElementById('status');

  // 加载当前设置
  function loadSettings () {
    chrome.storage.sync.get([
      'enableNotifications',
      'enableSound',
      'alertInterval',
      'soundType'
    ], function (result) {
      // 使用传统方式设置默认值，避免空值合并运算符
      enableNotificationsCheckbox.checked = (typeof result.enableNotifications !== 'undefined') ? result.enableNotifications : true;
      enableSoundCheckbox.checked = (typeof result.enableSound !== 'undefined') ? result.enableSound : true;
      alertIntervalInput.value = (typeof result.alertInterval !== 'undefined') ? result.alertInterval : 5;
      soundTypeSelect.value = (typeof result.soundType !== 'undefined') ? result.soundType : 'beep';

      console.log('设置已加载:', result);
    });
  }

  // 保存设置
  function saveSettings () {
    var settings = {
      enableNotifications: enableNotificationsCheckbox.checked,
      enableSound: enableSoundCheckbox.checked,
      alertInterval: parseInt(alertIntervalInput.value, 10),
      soundType: soundTypeSelect.value
    };

    chrome.storage.sync.set(settings, function () {
      if (chrome.runtime.lastError) {
        console.error('保存设置失败:', chrome.runtime.lastError);
        showStatus('保存失败！', 'error');
      } else {
        console.log('设置已保存:', settings);
        showStatus('设置已保存！', 'success');

        // 通知background script设置已更新
        chrome.runtime.sendMessage({
          type: 'settingsUpdated',
          settings: settings
        });
      }
    });
  }

  // 显示状态消息
  function showStatus (message, type) {
    statusDiv.textContent = message;
    statusDiv.className = 'status ' + type;
    statusDiv.style.display = 'block';

    // 3秒后隐藏状态消息
    setTimeout(function () {
      statusDiv.style.display = 'none';
    }, 3000);
  }

  // 测试通知功能
  function testNotification () {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      if (tabs[0]) {
        chrome.tabs.sendMessage(tabs[0].id, {
          type: 'showNotification',
          title: '测试通知',
          message: '这是一个测试通知，如果您看到这个消息，说明通知功能正常工作。',
          alertType: 'info',
          playSound: enableSoundCheckbox.checked,
          flashTitle: true
        });
      }
    });
    showStatus('测试通知已发送！', 'info');
  }

  // 测试声音功能
  function testSound () {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      if (tabs[0]) {
        chrome.tabs.sendMessage(tabs[0].id, {
          type: 'playSound',
          soundType: soundTypeSelect.value
        });
      }
    });
    showStatus('测试音效已播放！', 'info');
  }

  // 获取插件状态
  function getPluginStatus () {
    chrome.runtime.sendMessage({ type: 'getSettings' }, function (response) {
      if (response) {
        var statusText = '插件状态：正常运行\n';
        statusText += '通知：' + (response.enableNotifications ? '启用' : '禁用') + '\n';
        statusText += '声音：' + (response.enableSound ? '启用' : '禁用') + '\n';
        statusText += '检查间隔：' + response.alertInterval + '分钟\n';
        statusText += '声音类型：' + response.soundType;

        document.getElementById('pluginStatus').textContent = statusText;
      }
    });
  }

  // 绑定事件监听器
  if (saveButton) {
    saveButton.addEventListener('click', saveSettings);
  }

  // 添加测试按钮事件监听器
  var testNotificationButton = document.getElementById('testNotification');
  if (testNotificationButton) {
    testNotificationButton.addEventListener('click', testNotification);
  }

  var testSoundButton = document.getElementById('testSound');
  if (testSoundButton) {
    testSoundButton.addEventListener('click', testSound);
  }

  // 验证输入值
  if (alertIntervalInput) {
    alertIntervalInput.addEventListener('input', function () {
      var value = parseInt(this.value, 10);
      if (isNaN(value) || value < 1) {
        this.value = 1;
      } else if (value > 60) {
        this.value = 60;
      }
    });
  }

  // 实时保存设置（当用户更改时）
  function bindRealTimeSave () {
    var elements = [enableNotificationsCheckbox, enableSoundCheckbox, alertIntervalInput, soundTypeSelect];

    for (var i = 0; i < elements.length; i++) {
      if (elements[i]) {
        elements[i].addEventListener('change', function () {
          // 延迟保存，避免频繁操作
          setTimeout(saveSettings, 300);
        });
      }
    }
  }

  // 显示版本信息
  function showVersionInfo () {
    var manifest = chrome.runtime.getManifest();
    var versionElement = document.getElementById('version');
    if (versionElement) {
      versionElement.textContent = '版本: ' + manifest.version + ' (Chrome 65兼容版)';
    }
  }

  // 检查权限状态
  function checkPermissions () {
    var permissionsElement = document.getElementById('permissions');
    if (permissionsElement) {
      // 检查通知权限
      if ('Notification' in window) {
        if (Notification.permission === 'granted') {
          permissionsElement.textContent = '通知权限：已授权';
          permissionsElement.className = 'permission-status granted';
        } else if (Notification.permission === 'denied') {
          permissionsElement.textContent = '通知权限：已拒绝';
          permissionsElement.className = 'permission-status denied';
        } else {
          permissionsElement.textContent = '通知权限：等待授权';
          permissionsElement.className = 'permission-status pending';
        }
      } else {
        permissionsElement.textContent = '通知权限：不支持';
        permissionsElement.className = 'permission-status unsupported';
      }
    }
  }

  // 初始化
  function initialize () {
    console.log('初始化popup界面');
    loadSettings();
    bindRealTimeSave();
    showVersionInfo();
    checkPermissions();
    getPluginStatus();
  }

  // 开始初始化
  initialize();

  console.log('Chrome 65兼容版 popup.js 初始化完成');
});